﻿<p>Non streaming component with persistent state</p>

<p>This component demonstrates state persistence in the absence of streaming rendering. When the component renders it will try to restore the state and if present display that it succeeded in doing so and the restored value. If the state is not present, it will indicate it didn't find it and display a "fresh" value.</p>

<p id="interactive">Interactive: @(!RunningOnServer)</p>
<p id="interactive-runtime">Interactive runtime: @_interactiveRuntime</p>
<p id="state-found">State found:@_stateFound</p>
<p id="state-value">State value:@_stateValue</p>

@code {

    private bool _stateFound;
    private string _stateValue;
    private string _interactiveRuntime;

    [Inject] public PersistentComponentState PersistentComponentState { get; set; }

    [CascadingParameter(Name = nameof(RunningOnServer))] public bool RunningOnServer { get; set; }
    [Parameter] public string ServerState { get; set; }

    protected override void OnInitialized()
    {
        PersistentComponentState.RegisterOnPersisting(PersistState);

        _stateFound = PersistentComponentState.TryTakeFromJson<string>("NonStreamingComponentWithPersistentState", out _stateValue);

        if (!_stateFound)
        {
            _stateValue = "fresh";
        }

        if (RunningOnServer)
        {
            _interactiveRuntime = "none";
            _stateFound = true;
            _stateValue = ServerState ?? "restored";
        }
        else
        {
            _interactiveRuntime = OperatingSystem.IsBrowser() ? "wasm" : "server";
        }
    }

    Task PersistState()
    {
        PersistentComponentState.PersistAsJson("NonStreamingComponentWithPersistentState", _stateValue);
        return Task.CompletedTask;
    }
}
